// pages/firmOrder/index.js
var util = require('../../utils/util.js');
var WxParse = require('../../utils/wxParse/wxParse.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //
    _num: 0,
    trip: {
      title: '',
      date: ''
    },
    orderDetail: '',
    userList: [],
    result: [],
    addUserList: [],
    addUserResult: [],
    allChecked: false,
    addUserPopupShow: false,
    payTypeSel: '2',
    balancePay: true,
    wxPay: false,
    comments: '',
    agreementOrderCheck: true,
    agreementOrderShow: false,
    agreementServiceCheck: true,
    agreementServiceShow: false,
    integral: '',
    balance: '',
    addId: [],
    addList: [],
    choseAdd: [],
    adultNum: 0,
    childrenNum: 0,
    totalPrice: 0,
    paidPrice: 0,
    name: '',
    mobile: '',
    orderInfo: '',
    orderAgree: '',
    routerAgree: '',
    source: 1,
    showMask: true
  },
  onLoad: function (options) {
    console.log(options)
    if (options.source) {
      this.data.source = options.source
    }
  },
  onShow: function (options) {
    this.init();
  },
  /**
   * 出行人信息
   */
  init() {
    let that = this;
    wx.getStorage({
      key: 'orderInfo',
      success(orderInfo) {
        if (orderInfo.data.out_trade_no) {
          util.http({
            url: 'api/miniwechat/order/order',
            method: 'GET',
            data: orderInfo.data
          }).then(res => {
            that.data.orderInfo = orderInfo.data
            WxParse.wxParse('routerAgree', 'html', res.protocol, that, 5);
            res.people.forEach((item, index) => {
              switch (item.card_type) {
                case 1:
                  item.card_type = '身份证'
                  break;
                case 2:
                  item.card_type = '通行证'
                  break;
              }
            })
            that.setData({
              orderDetail: res,
              addList: res.people,
              integral: {
                used: 0,
                available: res.score,
                deduction: 0.00
              },
              balance: {
                used: 0,
                available: res.money,
                deduction: 0.00
              }
            })
            console.log(res.people,)
            if (that.data.addUserResult.length > 0) {
              that.addUserConfirm();
              that.initNum();
            } else {
              res.people.forEach((item, index) => {
                if (item.default == 1) {
                  // 查看样式
                  console.log(item)
                  that.setData({
                    addUserResult: [String(index)],
                    addId: [item.id],
                    choseAdd: [item],
                    adultNum: 1
                  })
                  that.initNum();
                }
              })
            }

          }).catch(err => {
            wx.showToast({
              title: String(err),
              icon: 'none',
              duration: 2000
            })
          })
        } else {
          util.http({
            url: 'api/miniwechat/order/create_order',
            method: 'POST',
            data: orderInfo.data
          }).then(res => {
            orderInfo.data.out_trade_no = res.out_trade_no
            that.data.orderInfo = orderInfo.data
            wx.setStorage({
              key: 'orderInfo',
              data: that.data.orderInfo
            })
            util.http({
              url: 'api/miniwechat/order/order',
              method: 'GET',
              data: orderInfo.data
            }).then(res => {
              WxParse.wxParse('routerAgree', 'html', res.protocol, that, 5);
              res.people.forEach((item, index) => {
                switch (item.card_type) {
                  case 1:
                    item.card_type = '身份证'
                    break;
                  case 2:
                    item.card_type = '通行证'
                    break;
                }
              })
              that.setData({
                orderDetail: res,
                addList: res.people,
                integral: {
                  used: '',
                  available: res.score,
                  deduction: 0.00
                },
                balance: {
                  used: '',
                  available: res.money,
                  deduction: 0.00
                }
              })
              if (that.data.addUserResult.length > 0) {
                that.addUserConfirm();
                that.initNum();
              } else {
                res.people.forEach((item, index) => {
                  if (item.default == 1) {
                    that.setData({
                      addUserResult: [String(index)],
                      addId: [item.id],
                      choseAdd: [item],
                      adultNum: 1
                    })
                    that.initNum();
                  }
                })
              }

            }).catch(err => {
              wx.showToast({
                title: String(err),
                icon: 'none',
                duration: 2000
              })
            })
          }).catch(err => {
            wx.showToast({
              title: String(err),
              icon: 'none',
              duration: 2000
            })
          })
        }

      }
    })
    util.http({
      url: 'api/miniwechat/user/service_agree'
    }).then(res => {
      console.log(res)
      WxParse.wxParse('orderAgree', 'html', res.trading_agreement, that, 5)
    }).catch(err => {
      wx.showToast({
        title: String(err),
        icon: 'none',
        duration: 2000
      })
    })
  },
  // 点击出行人信息切换高亮盒子以及修改个人新人
  menuClick: function (e) {
    console.log('触发点击事件')
    this.setData({
      _num: e.currentTarget.dataset.num
    })
  },
  onChange(event) {
    this.setData({
      result: event.detail
    });
  },
  onAllChecked(event) {
    this.setData({
      allChecked: event.detail
    })
    if (event.detail) {
      let len = this.data.userList.length,
        arr = [];
      for (let i = 0; i < len; i++) {
        arr.push(i + '');
      }
      this.setData({
        result: arr
      })
    } else {
      this.setData({
        result: []
      })
    }
  },
  onDeleteUser() {
    let res = this.data.result,
      arr = this.data.userList.filter(function (cur, index) {
        return res.indexOf(index + '') == -1;
      });
    this.setData({
      userList: arr,
      result: [],
      allChecked: false
    })
  },
  // 这个是微信小程序中的弹框
  showAddUserPopup() {
    this.setData({
      showMask: false,
      addUserPopupShow: true
    })
  },
  closeAddUserPopup() {
    this.setData({
      showMask: true,
      addUserPopupShow: false
    })
  },
  //添加出行人
  toggle(event) {
    const name = event.currentTarget.dataset.name;
    const checkbox = this.selectComponent(`.checkboxes-${name}`);
    checkbox.toggle();
  },
  addUserConfirm() {
    let arr = [],
      arrId = []
    this.data.addUserResult.forEach(item => {
      arr.push(this.data.addList[item]);
      arrId.push(this.data.addList[item].id)
    })
    this.setData({
      addId: arrId,
      choseAdd: arr,
      addUserPopupShow: false
    })
    this.initNum();
  },
  onAddUser(event) {
    this.setData({
      addUserResult: event.detail
    })
  },
  delAdd() {
    console.log(this.data._num)
    this.data.choseAdd.splice(this.data._num, 1);
    this.data.addUserResult.splice(this.data._num, 1);
    this.data.addId.splice(this.data._num, 1);
    this.setData({
      addUserResult: this.data.addUserResult,
      choseAdd: this.data.choseAdd,
      _num: 0
    })
    this.initNum();
  },
  initNum() {
    let i = 0,
      j = 0;
    this.data.choseAdd.forEach((item, index) => {
      if (item.person_type == 3 || item.person_type == 4) {
        i++;
      } else {
        j++
      }
    })
    let totalPrice = (this.data.orderDetail.adult_price * j) + (this.data.orderDetail.children_price * i)
    this.setData({
      adultNum: j,
      childrenNum: i,
      paidPrice: totalPrice,
      totalPrice: totalPrice,
    })

  },
  /**
   * 积分抵扣
   */
  onIntegralChange(event) {
    let confirmIntegral = event.detail.value,
      ded = confirmIntegral / 100;
    if (ded > this.data.totalPrice - this.data.balance.deduction) {
      confirmIntegral = Math.round((this.data.totalPrice - this.data.balance.deduction) * 100),
        ded = confirmIntegral / 100;
    }
    // let confirmIntegral = Number(event.detail.value > this.data.integral.available ? this.data.integral.available : event.detail.value),
    //   ded = (confirmIntegral / 100).toFixed(2);
    // if (ded > this.data.totalPrice) {
    //   confirmIntegral = this.data.totalPrice * 100;
    //   ded = (confirmIntegral / 100).toFixed(2);
    //   if (confirmIntegral > this.data.paidPrice) {
    //     confirmIntegral = this.data.paidPrice * 100;
    //     ded = (confirmIntegral / 100).toFixed(2);
    //   }
    // }
    this.setData({
      ['integral.used']: confirmIntegral,
      ['integral.deduction']: ded.toFixed(2),
      paidPrice: (this.data.totalPrice - this.data.balance.deduction  - ded).toFixed(2)
    })
  },
  setAllIntegral() {
    let confirmIntegral = this.data.integral.available,
      ded = confirmIntegral / 100;
    if (ded > this.data.totalPrice - this.data.balance.deduction) {
      confirmIntegral = Math.round((this.data.totalPrice - this.data.balance.deduction) * 100),
        ded = confirmIntegral / 100;
    }
    this.setData({
      ['integral.used']: confirmIntegral,
      ['integral.deduction']: ded.toFixed(2),
      paidPrice: (this.data.totalPrice - this.data.balance.deduction - ded).toFixed(2)
    })
  },
  onBalanceChange(event) {
    let confirmBalance = event.detail.value;
    if (confirmBalance > this.data.totalPrice - this.data.integral.deduction) {
      confirmBalance = (this.data.totalPrice - this.data.integral.deduction).toFixed(2)
    }
  
    this.setData({
      ['balance.used']: confirmBalance,
      ['balance.deduction']: confirmBalance,
      paidPrice: (this.data.totalPrice - this.data.integral.deduction - confirmBalance).toFixed(2)
    })
  },
  setAllBalance() {
    let confirmBalance = this.data.balance.available;
    if (confirmBalance > this.data.totalPrice - this.data.integral.deduction) {
      confirmBalance = (this.data.totalPrice - this.data.integral.deduction).toFixed(2)
    }
    this.setData({
      ['balance.used']: confirmBalance,
      ['balance.deduction']: confirmBalance,
      paidPrice: (this.data.totalPrice - this.data.integral.deduction - confirmBalance).toFixed(2)
    })
  },
  /**
   * 支付方式
   */
  onPayTypeSel(event) {
    this.setData({
      payTypeSel: event.detail
    })
  },
  onPayTypeClick(event) {
    this.setData({
      payTypeSel: event.currentTarget.dataset.name
    })
  },
  onBalancePay(event) {
    this.setData({
      balancePay: event.detail
    })
    if (event.detail) {
      this.setData({
        wxPay: false
      })
    }
  },
  onWxPay(event) {
    this.setData({
      wxPay: event.detail
    })
    if (event.detail) {
      this.setData({
        balancePay: false
      })
    }
  },
  /**
   * 留言
   */
  onComments(e) {
    let detail = e.detail
    this.setData({
      comments: detail
    })
  },
  /**
   * 协议
   */
  onAgreementOrderCheck(event) {
    this.setData({
      agreementOrderCheck: event.detail
    })
  },
  showAgreementOrder() {
    this.setData({
      showMask: false,
      agreementOrderShow: true
    })
  },
  closeAgreementOrder() {
    this.setData({
      showMask: true,
      agreementOrderShow: false
    })
  },
  onAgreementServiceCheck(event) {
    this.setData({
      agreementServiceCheck: event.detail
    })
  },
  showAgreementService() {
    this.setData({
      showMask: false,
      agreementServiceShow: true
    })
  },
  closeAgreementService() {
    this.setData({
      showMask: true,
      agreementServiceShow: false
    })
  },
  changeName(e) {
    this.data.name = e.detail.value
  },
  changePhone(e) {
    this.data.mobile = e.detail.value
  },
  pay() {
    let that = this;
    if (!this.data.agreementOrderCheck || !this.data.agreementServiceCheck) {
      return false;
    }
    let phone = /^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0-8])|(18[0-9])|166|198|199|(147))\d{8}$/;
    if (this.data.adultNum === 0) {
      wx.showToast({
        title: '未选择出行人或未选择成人',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (this.data.orderDetail.is_home == 2) {
      let i = 0;
      this.data.choseAdd.forEach(item => {
        if (item.passport_number == '') {
          wx.showToast({
            title: '国外线路出行人需填写护照号码',
            icon: 'none',
            duration: 2000
          })
          i++;
          return false;
        }
        if (item.surname == '') {
          wx.showToast({
            title: '国外线路出行人需填写性(拼音)',
            icon: 'none',
            duration: 2000
          })
          i++;
          return false;
        }
        if (item.name == '') {
          wx.showToast({
            title: '国外线路出行人需填写名(拼音)',
            icon: 'none',
            duration: 2000
          })
          i++;
          return false;
        }
      })
      if (i > 0) {
        return;
      }
    }
    if (this.data.name === '') {
      wx.showToast({
        title: '联系人姓名为空',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (this.data.mobile === '') {
      wx.showToast({
        title: '联系人手机号码为空',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (!(phone.test(this.data.mobile))) {
      wx.showToast({
        title: '联系人手机号码不正确',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (!this.data.agreementOrderCheck) {
      wx.showToast({
        title: '未同意《全新体验线路订购协议》',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (!this.data.agreementServiceCheck) {
      wx.showToast({
        title: '未同意《线路服务协议》',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (this.data.payTypeSel == 2) {
      if (this.data.paidPrice == 0) {
        that.data.payTypeSel = 1;
      }
      util.http({
        url: 'api/miniwechat/order/order',
        method: 'POST',
        data: {
          user_id: that.data.orderInfo.user_id,
          line_id: that.data.orderInfo.line_id,
          line_time_id: that.data.orderInfo.line_time_id,
          out_trade_no: that.data.orderInfo.out_trade_no,
          people_ids: that.data.addId,
          name: that.data.name,
          mobile: that.data.mobile,
          integral_ded: that.data.integral.used,
          children_num: that.data.childrenNum,
          adult_num: that.data.adultNum,
          sum_money: that.data.totalPrice,
          paid_price: that.data.paidPrice,
          remark: that.data.comments,
          pay_type: that.data.payTypeSel,
          money_ded: that.data.balance.used
        }
      }).then(datas => {
        if(this.data.paidPrice == 0) {
          wx.redirectTo({
            url: '/pages/paySuccess/index?state=1' + '&orderId=' + datas.id
          })
          return;
        }
        util.http({
          url: 'api/miniwechat/order/pay',
          method: 'POST',
          isPay: true,
          data: {
            out_trade_no: datas.out_trade_no,
            source: that.data.source
          }
        }).then(res => {
          wx.requestPayment({
            timeStamp: String(res.timeStamp),
            nonceStr: String(res.nonceStr),
            package: String(res.package),
            signType: String(res.signType),
            paySign: String(res.paySign),
            success(resx) {
              wx.redirectTo({
                url: '/pages/paySuccess/index?state=1' + '&orderId=' + datas.id
              })
            },
            fail(res) {
              console.log(res)
              wx.redirectTo({
                url: '/pages/paySuccess/index?state=0'
              })
            }
          })
        }).catch(err => {
          wx.showToast({
            title: String(err),
            icon: 'none',
            duration: 2000
          })
        })
      }).catch(err => {
        wx.showToast({
          title: String(err),
          icon: 'none',
          duration: 2000
        })
      })
    } else {
      wx.showToast({
        title: '未开放',
        icon: 'none',
        duration: 2000
      })
    }
  },
  editTravelerInfo(e) {
    wx.navigateTo({
      url: '/pages/addTraveler/index?id=' + e.currentTarget.dataset.id
    })
  },
})